package com.tubeonfire.controller.admin;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tubeonfire.entity.Playlist;
import com.tubeonfire.model.admin.PlaylistModel;
import com.tubeonfire.util.PlaylistValidate;
import com.tubeonfire.util.IdUniqueHelper;

@SuppressWarnings("serial")
public class AddPlaylistServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(AddPlaylistServlet.class
			.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		try {
			HttpSession session = req.getSession();
			if (session.getAttribute("return") == null) {
				Playlist pl = new Playlist();
				session.setAttribute("pl", pl);
			}			
			session.setAttribute("action", "add");
			req.getRequestDispatcher("/admin/form_playlist.jsp").forward(req,
					resp);
		} catch (Exception e) {
			log.warning(e.toString());			
			e.printStackTrace(System.err);
			resp.sendError(4004, "We are sorry for the inconvenience ! Please try again later !");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			HttpSession session = req.getSession();
			Playlist pl = new Playlist();
			if (PlaylistValidate.checkForm(req, resp, session, "add", pl)) {
				pl.setId(IdUniqueHelper.getId());
				PlaylistModel.insert(pl);
				session.removeAttribute("pl");
				session.setAttribute("action", "add");
				session.setAttribute("success", "Action success !");
				resp.sendRedirect("/admin/playlist/add");
			}
		} catch (Exception e) {
			log.warning(e.toString());
			e.printStackTrace(System.err);
			resp.sendError(4004, "We are sorry for the inconvenience ! Please try again later !");
		}
	}
}
